package com.example.myapplicationktkt2.webview


import android.annotation.SuppressLint
import android.content.ContentValues.TAG
import android.os.Bundle
import android.util.Log
import android.webkit.JavascriptInterface
import android.webkit.WebChromeClient
import android.webkit.WebView
import androidx.activity.ComponentActivity
import com.example.myapplicationktkt2.notification.NotificationHelper

class webviewNotification : ComponentActivity() {
    @SuppressLint("SetJavaScriptEnabled")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val webView = WebView(this)
        setContentView(webView)

        webView.settings.javaScriptEnabled = true
        webView.webChromeClient = WebChromeClient()

        // JS Bridge
        webView.addJavascriptInterface(object {
            @JavascriptInterface
            fun notifyFromWeb(msg: String) {
                Log.d(TAG, "notifyFromWeb: $msg")
                NotificationHelper.sendNotification(this@webviewNotification, msg)
            }
        }, "AndroidBridge")

        // 加载本地 HTML
        val html = """
            <html>
            <body>
                <h3>WebView 页面</h3>
                <button onclick="window.AndroidBridge.notifyFromWeb('这是来自 H5 的通知')">
                    触发通知
                </button>
            </body>
            </html>
        """.trimIndent()
        webView.loadDataWithBaseURL(null, html, "text/html", "utf-8", null)
    }
}
